<?php

namespace App\Http\Controllers\Api\SmallApp\Order;

use App\Http\Controllers\Common\ApiController;
use App\Models\Constant\OrderConstant;
use App\Models\Constant\UserConstant;
use App\Models\Order\Order;
use App\Models\Repair\RepairFactoryAdmin;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MyOrderController extends ApiController {

    public function appointRepairFactoryIndex(Request $request) {

        $token = $request->header('token');
        $userId = checkJWT($token)['id'];
        $user = User::where(['id'=>$userId])->first();
        $page = $request->input('page',1);
        $page_size = $request->input('page_size',20);
        $type = $request->input('type',1);

        $status = $request->input('status',OrderConstant::STATUS_WAIT_RECEIVING);
        $conditions = compact('status');

        if($type==UserConstant::TYPE_NORMAL){
            $conditions['userId'] = $userId;
            $conditions['repairFactoryId'] = null;
        }
        Log::info('userId:'.$userId.',type:'.$type);
        //说明是工厂管理员访问该列表
        if($type==UserConstant::TYPE_REPAIR){
            $conditions['userId'] = null;
            $conditions['repairFactoryId'] = RepairFactoryAdmin::where(['phone'=>$user->phone])->first()
                ->factory_id??-1;
        }

        $this->getCol = ['id','created_at','case_number','car_number','status'];
        $order = new Order();
        $records = $order->getLst($conditions);
        if($status==OrderConstant::STATUS_END && $type==UserConstant::TYPE_NORMAL){
            $records = $records->where('repair_factory_id','!=',0);
        }
        $records = $records->with(['owner:id,real_name,phone'])->paginate($page_size,$this->getCol,'page',$page);

        foreach ($records as $record) {
            $record->status_name = OrderConstant::MAP_STATUS[$record->status]??'未知';
        }

        $countReceiving =  $order->getLst(['status'=>OrderConstant::STATUS_WAIT_RECEIVING,'userId'=>$conditions['userId'],'repairFactoryId'=>$conditions['repairFactoryId']])->count(['id']);
        $countRepairing =  $order->getLst(['status'=>OrderConstant::STATUS_WAIT_REPAIRING,'userId'=>$conditions['userId'],'repairFactoryId'=>$conditions['repairFactoryId']])->count(['id']);
        $countWaitRepair =  $order->getLst(['status'=>OrderConstant::STATUS_WAIT_REPAIR,'userId'=>$conditions['userId'],'repairFactoryId'=>$conditions['repairFactoryId']])->count(['id']);

        if($type==UserConstant::TYPE_NORMAL){
            $countEnd =  $order->getLst(['status'=>OrderConstant::STATUS_END,'userId'=>$conditions['userId'],'repairFactoryId'=>$conditions['repairFactoryId']])
                ->where('repair_factory_id','!=',0)
                ->count(['id']);
        }else{
            $countEnd =  $order->getLst(['status'=>OrderConstant::STATUS_END,'userId'=>$conditions['userId'],'repairFactoryId'=>$conditions['repairFactoryId']])
                ->count(['id']);
        }


        $mapStatus = OrderConstant::MAP_STATUS;
        return responseSuccess($records->items(),$records->total(),100000,compact('countReceiving','countRepairing','countEnd','countWaitRepair','mapStatus'));
    }

    public function receiveOrder(Request $request) {
        $id = $request->input('id');
        $order = Order::where(compact('id'))->first();
        if($order->status==OrderConstant::STATUS_CANCEL)
            return responseFail('订单已经取消了！');
        Order::where(compact('id'))->update(['status'=>OrderConstant::STATUS_WAIT_REPAIR,'reason'=>null]);
        $order = Order::where(compact('id'))->first();
        return responseSuccess($order->toArray());
    }

    public function startRepair(Request $request) {
        $id = $request->input('id');
        $order = Order::where(compact('id'))->first();
        if($order->status==OrderConstant::STATUS_CANCEL)
            return responseFail('订单已经取消了！');
        Order::where(compact('id'))->update(['status'=>OrderConstant::STATUS_WAIT_REPAIRING,'reason'=>null]);
        $order = Order::where(compact('id'))->first();
        return responseSuccess($order->toArray());
    }

    public function repaired(Request $request) {
        $id = $request->input('id');
        $qianzi_url = $request->input('qianzi_url');
        $repaired_urls = $request->input('repaired_urls');

        Log::info('qianzi',compact('qianzi_url'));

        $this->validate($request, [
            'id'=>'required',
            'qianzi_url'=>'required',
            'repaired_urls'=>'required',
        ],[],[
            'qianzi_url'=>'客户签字图片',
            'repaired_urls'=>'汽车修补照片'
        ]);

        $order = Order::where(compact('id'))->first();
        if($order->status==OrderConstant::STATUS_CANCEL)
            return responseFail('订单已经取消了！');
        Order::where(compact('id'))->update(['status'=>OrderConstant::STATUS_END,'qianzi_url'=>$qianzi_url,
            'repaired_urls'=>$repaired_urls,
            'reason'=>null]);
        $order = Order::where(compact('id'))->first();
        return responseSuccess($order->toArray());
    }

    /**
     * 自主维修 - 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function selfRepairIndex(Request $request) {
        $token = $request->header('token');
        $userId = checkJWT($token)['id'];

        $page = $request->input('page',1);
        $page_size = $request->input('page_size',20);

        $status = $request->input('status',OrderConstant::STATUS_WAIT_HUMAN_CHECK);
        $conditions = compact('userId','status');
        //$this->getCol = ['created_at','case_number','car_number','status','id'];
        $this->getCol = ['*'];
        $order = new Order();
        $records = $order->getLst($conditions);

        //如果是自主维修的，又是已完成列表，那查询的出来的“已完成的单子”必须是 自主维修已完成的，也就是没经过工厂的
        if($status==OrderConstant::STATUS_END){
            $records = $records->where('repair_factory_id',0);
        }
        $records = $records->paginate($page_size,$this->getCol,'page',$page);

        foreach ($records as $record) {
            $record->status_name = OrderConstant::MAP_STATUS[$record->status]??'未知';
            if(!empty($record->car_number)){
                $record->number = '车牌号:'.$record->car_number;
            }else{
                $record->number = '车架号:'.$record->car_jia_number;
            }
        }
        $countWaitCheck = $order->getLst(['status'=>[OrderConstant::STATUS_WAIT_AUTO_CHECK,OrderConstant::STATUS_WAIT_HUMAN_CHECK,OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK],'userId'=>$userId])->count(['id']);
        $countOff =  $order->getLst(['status'=>OrderConstant::STATUS_WAIT_OFF,'userId'=>$userId])->count(['id']);
        $countRepay =  $order->getLst(['status'=>OrderConstant::STATUS_WAIT_REPAY,'userId'=>$userId])->count(['id']);
        $countEnd =  $order->getLst(['status'=>OrderConstant::STATUS_END,'userId'=>$userId])->where('repair_factory_id',0)->count(['id']);
        $countCheckNotPass = $order->getLst(['status'=>OrderConstant::STATUS_CHECK_NOT_PASS,'userId'=>$userId])->count(['id']);

        $mapStatus = OrderConstant::MAP_STATUS;
        return responseSuccess($records->items(),$records->total(),100000,compact('countWaitCheck','countOff','countRepay','countEnd','countCheckNotPass','mapStatus'));


    }


}
